<?php
/**
 * Service of Product
 *
 * @author guzhi
 * @since 2009-03-25
 */

require_once BaseUtil::getModulePath("base")  .  '/services/BaseService.php';
require_once BaseUtil::getModulePath("inventory")  .  '/models/ProductDao.php';
require_once BaseUtil::getModulePath("inventory")  .  '/models/ProductItemDao.php';
require_once BaseUtil::getModulePath('dbgrid') . '/DBGrid.php';
require_once BaseUtil::getModulePath("department")  .  '/models/DepartmentDao.php';
require_once BaseUtil::getModulePath("inventory")  .  '/models/CategoryProductDao.php';
require_once BaseUtil::getModulePath("metadata")  .  '/models/MetadataDao.php';
require_once BaseUtil::getModulePath("metadata")  .  '/models/MetadataSetDao.php';
require_once BaseUtil::getModulePath("metadata")  .  '/models/MetadataOptionDao.php';
require_once BaseUtil::getModulePath("inventory")  .  '/models/ItemMetadataDao.php';
require_once BaseUtil::getModulePath("component")  .  '/Number.php';
require_once BaseUtil::getModulePath("systemlog")  .  '/services/SystemLogService.php';

require_once BaseUtil::getModulePath("inventory")  .  '/models/ProductImageDao.php';

class ProductService extends BaseService {

    private $productDao;

    private $productItemDao;

    private $categoryProductDao;

    private $metadataDao;

    private $metadataSetDao;

    private $metadataOptionDao;

    private $itemMetadataDao;

    private $categoryDao;
    
    private $productImageDao;

    public function __construct() {
        parent::__construct();
        $this->productDao = new ProductDao();
        $this->productDao->setDb($this->db);
        $this->productItemDao = new ProductItemDao();
        $this->productItemDao->setDb($this->db);
        $this->categoryProductDao = new CategoryProductDao();
        $this->categoryProductDao->setDb($this->db);
        $this->metadataDao = new MetadataDao();
        $this->metadataDao->setDb($this->db);
        $this->metadataSetDao = new MetadataSetDao();
        $this->metadataSetDao->setDb($this->db);
        $this->metadataOptionDao = new MetadataOptionDao();
        $this->metadataOptionDao->setDb($this->db);
        $this->itemMetadataDao = new ItemMetadataDao();
        $this->itemMetadataDao->setDb($this->db);
        $this->categoryDao = new CategoryDao();
        $this->categoryDao->setDb($this->db);
        $this->productImageDao = new ProductImageDao();
        $this->productImageDao->setDb($this->db);
    }

    public function addProduct($form,$post) {
        //insert product
        $setId = trim($_POST['metadataSetId']);        
        $product = array();
        $product['department_id'] = $form->getValue("department");
        $product['title'] = $form->getValue("title");
        $product['url_title'] = HttpUtil::iReplaceAllUrlStr($form->getValue("urlTitle"));
        $product['description'] = $form->getValue("description");
        $product['related_1'] = $form->getValue("related1");
        $product['related_2'] = $form->getValue("related2");
        $product['related_3'] = $form->getValue("related3");
        $product['related_4'] = $form->getValue("related4");
        $product['seo_title'] = $form->getValue("seoTitle");
        $product['seo_keyword'] = $form->getValue("seoKeyword");
        $product['seo_description'] = $form->getValue("seoDescription");
        $product['cheque_rule'] = $form->getValue("chequeRule");
        $product['price_rule'] = $form->getValue("priceRule");
        $product['ship_rule'] = $form->getValue("shipRule");
        $product['related_rule'] = $form->getValue("relatedRule");
        $product['templete'] = $form->getValue("templete");
        $product['metadata_set_id'] = $setId;
        $productId = $this->productDao->addProduct($product);
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('ADDPRO',$loginUser['uname'], $product);         
        //insert product category
        $categoryIdStr = $post["categoryId"];
        if(!empty($categoryIdStr)) {
            $categoryIds = explode(",", $categoryIdStr);
            foreach($categoryIds as $categoryId) {
                $categoryId = trim($categoryId);
                if(!empty($categoryId) && $categoryId != "-1") {
                    $categoryProduct = array("category_id" => $categoryId , "product_id" => $productId);
                    $this->categoryProductDao->insertCategoryProduct($categoryProduct);
                }
            }
        }
        //insert product attributes
        //attribute name
        //        $attributes1s = isset($post['attribute0']) ? $post['attribute0'] : null;
        //        $attributes2s = isset($post['attribute1']) ? $post['attribute1'] : null;
        //        $attributes3s = isset($post['attribute2']) ? $post['attribute2'] : null;
        //        $attributes4s = isset($post['attribute3']) ? $post['attribute3'] : null;
        //        $attributes5s = isset($post['attribute4']) ? $post['attribute4'] : null;
        $attribute = isset($post['attribute']) ? $post['attribute'] : null;
        //attribute value
        $value1s = isset($post['value0']) ? $post['value0'] : null;
        $value2s = isset($post['value1']) ? $post['value1'] : null;
        $value3s = isset($post['value2']) ? $post['value2'] : null;
        $value4s = isset($post['value3']) ? $post['value3'] : null;
        $value5s = isset($post['value4']) ? $post['value4'] : null;
        $defaultItemValue =  $post['defaultItemVal'];
        $upcs = $post['upc'];
        //$skus = $post['sku'];
        $pPrices = $post['pPrice'];
        $cPrices = $post['cPrice'];
        $mPrices = $post['mPrice'];
        $lPrices = $post['lPrice'];
        $sPrices = $post['sPrice'];
        $weights = $post['weight'];
        $inventories = $post['inventory'];
        //$places = $post['place'];
        //$shippingTypes = $post['shippingType'];
        $freeShippingStatuses = $post['freeShippingStatus'];
        $visibles = $post['visible'];
        $defaultItems = explode(",",$defaultItemValue);
        //product metadata
        $pMetadataIds = $_POST['pMetadataId'];
        if(!empty($pMetadataIds)){
            $productMetadatas = $this->metadataDao->getMetedataByIds($pMetadataIds);
        }
        //item metadata
        $iMetadataIds = $_POST['iMetadataId'];
        if(!empty($iMetadataIds)){
            $itemMetadatas = $this->metadataDao->getMetedataByIds($iMetadataIds);
        }
  
        $i = 0;
        foreach ($pPrices as $pPrice) {            
            //$sku = trim($skus[$i]);
            $pPrice = trim($pPrice);
            $upc = trim($upcs[$i]);
            $cPrice = trim($cPrices[$i]);
            $mPrice = trim($mPrices[$i]);            
            $lPrice = trim($lPrices[$i]);
            $sPrice = trim($sPrices[$i]);
            $weight = trim($weights[$i]);
            $inventory = trim($inventories[$i]);
            //$place = trim($places[$i]);
            $defaultItem = $defaultItems[$i];
            //$shippingType = $shippingTypes[$i];
            //$freeShippingStatus = $freeShippingStatuses[$i];
            $visible = $visibles[$i];
            //if($upc != "" && $sku != ""){
            $attribute1 = "";
            $attribute2 = "";
            $attribute3 = "";
            $attribute4 = "";
            $attribute5 = "";
            $value1 = "";
            $value2 = "";
            $value3 = "";
            $value4 = "";
            $value5 = "";
            $key1 = "";
            $key2 = "";
            $key3 = "";
            $key4 = "";
            $key5 = "";
            $metadataId1 = "";
            $metadataId2 = "";
            $metadataId3 = "";
            $metadataId4 = "";
            $metadataId5 = "";
            if(isset($attribute) && isset($attribute[0]) && isset($value1s)) {
                $attribute1 = trim($attribute[0]);
                $itemAttribute1 = $this->getItemMetadataValue(0,trim($value1s[$i]),$iMetadataIds,$itemMetadatas);
                $value1 = $itemAttribute1['value'];
                $key1 = $itemAttribute1['key'];
                $metadataId1 = $itemAttribute1['metadataId'];
            }
            if(isset($attribute) && isset($attribute[1]) && isset($value2s)) {
                $attribute2 = trim($attribute[1]);
                $itemAttribute2 = $this->getItemMetadataValue(1,trim($value2s[$i]),$iMetadataIds,$itemMetadatas);
                $value2 = $itemAttribute2['value'];
                $key2 = $itemAttribute2['key'];
                $metadataId2 = $itemAttribute2['metadataId'];
            }
            if(isset($attribute) && isset($attribute[2]) && isset($value3s)) {
                $attribute3 = trim($attribute[2]);
                $itemAttribute3 = $this->getItemMetadataValue(2,trim($value3s[$i]),$iMetadataIds,$itemMetadatas);
                $value3 = $itemAttribute3['value'];
                $key3 = $itemAttribute3['key'];
                $metadataId3 = $itemAttribute3['metadataId'];
            }
            if(isset($attribute) && isset($attribute[3]) && isset($value4s)) {
                $attribute4 = trim($attribute[3]);
                $itemAttribute4 = $this->getItemMetadataValue(3,trim($value4s[$i]),$iMetadataIds,$itemMetadatas);
                $value4 = $itemAttribute4['value'];
                $key4 = $itemAttribute4['key'];
                $metadataId4 = $itemAttribute4['metadataId'];
            }
            if(isset($attribute) && isset($attribute[4]) && isset($value5s)) {
                $attribute5 = trim($attribute[4]);
                $itemAttribute5 = $this->getItemMetadataValue(4,trim($value5s[$i]),$iMetadataIds,$itemMetadatas);
                $value5 = $itemAttribute5['value'];
                $key5 = $itemAttribute5['key'];
                $metadataId5 = $itemAttribute5['metadataId'];
            }
            $productItem = array(
                "product_id" => $productId,
                "attribute_1" => $attribute1,
                "value_1" => $value1,
                "key_1" => $key1,
                "metadata_1" => $metadataId1,
                "attribute_2" => $attribute2,
                "value_2" => $value2,
                "key_2" => $key2,
                "metadata_2" => $metadataId2,
                "attribute_3" => $attribute3,
                "value_3" => $value3,
                "key_3" => $key3,
                "metadata_3" => $metadataId3,
                "attribute_4" => $attribute4,
                "value_4" => $value4,
                "key_4" => $key4,
                "metadata_4" => $metadataId4,
                "attribute_5" => $attribute5,
                "value_5" => $value5,
                "key_5" => $key5,
                "metadata_5" => $metadataId5,
                //"upc" => Number::getProductItemNumber($productId),
                //"sku" => $sku,
                "purchasing_price" => $pPrice,
                "cost_price" => $cPrice,
                "marketing_price" => $mPrice,
                "list_price" => $lPrice,
                "sale_price" => $sPrice,
                "weight" => $weight,
                "inventory" => $inventory,
                //"place" => $place,
                "default_item" => $defaultItem,
                //"shipping_type" => $shippingType,
                //"free_shipping_status" => $freeShippingStatus,
                "visible" => $visible
            );
            $itemId = $this->productItemDao->insertData($productItem);
            if(empty($upc)){
                $upc = Number::getProductItemNumber($itemId);
            }
            $productItem = array("upc" => $upc);
            $this->productItemDao->updateItem($itemId, $productItem);
            //insert item metedatas
            if(!empty($pMetadataIds)){
                foreach($pMetadataIds as $pMetadataId){
                    $metadata = $productMetadatas[$pMetadataId];
                    $inputType = $metadata['input_type'];
                    if(is_array($_POST['pMetadata'.$pMetadataId])){
                        $metadataValues = $_POST['pMetadata'.$pMetadataId];
                        if(empty($metadataValues)){
                             continue ;
                        }
                        foreach($metadataValues as $metadataValue){
                            $itemMetadata = array();
                            $itemMetadata['product_item_id'] = $itemId;
                            $itemMetadata['metadata_id'] = $pMetadataId;
                            if($inputType == 2){
                                $itemMetadata['desc_value'] = $metadataValue;
                            }else{
                                $itemMetadata['value'] = $metadataValue;
                            }
                            $this->itemMetadataDao->insertItemMetadata($itemMetadata);                              
                        }
                    }else{
                        $metadataValue = trim($_POST['pMetadata'.$pMetadataId]);
                        if(empty($metadataValue)){
                            continue ;
                        }
                        $itemMetadata = array();
                        $itemMetadata['product_item_id'] = $itemId;
                        $itemMetadata['metadata_id'] = $pMetadataId;
                        if($inputType == 2){
                            $itemMetadata['desc_value'] = $metadataValue;
                        }else{
                            $itemMetadata['value'] = $metadataValue;
                        }
                        $this->itemMetadataDao->insertItemMetadata($itemMetadata);                        
                    }
                }
            }
            if(!empty($iMetadataIds)){
                $j = 1;
                foreach($iMetadataIds as $iMetadataId){
                    $itemMetadata = array();
                    $value = "";
                    if($j == 1){
                        $value = trim($value1s[$i]);
                    }else if($j == 2){
                        $value = trim($value2s[$i]);
                    }else if($j == 3){
                        $value = trim($value3s[$i]);
                    }else if($j == 4){
                        $value = trim($value4s[$i]);
                    }else if($j == 5){
                        $value = trim($value5s[$i]);
                    }
                    $itemMetadata['product_item_id'] = $itemId;
                    $itemMetadata['metadata_id'] = $iMetadataId;
                    $itemMetadata['value'] = $value;
                    $this->itemMetadataDao->insertItemMetadata($itemMetadata);
                    $j++;
                }
            }
            //}
            $i++;
        }
        return $productId;
    }

    private function getItemMetadataValue($index,$value,$iMetadataIds,$itemMetadatas){
        $valueData = "";
        $keyData = "";
        $metadataId = "";
        if(isset($iMetadataIds[$index]) && !empty($iMetadataIds[$index])){
            $metadataId = $iMetadataIds[$index];
            $metadata = $itemMetadatas[$metadataId];
            $inputType = $metadata['input_type'];
            if($inputType == 3 || $inputType == 4 || $inputType == 6){
                $keyData = $value;
                $option = $this->metadataOptionDao->getOptionById($value);
                $valueData = $option['title'];
            }else{
                $valueData = $value;
            }
            return array(
                         "value" => $valueData,
                         "key" => $keyData,
                         "metadataId" => $metadataId
                        );
        }
    }

    public function editProduct($form,$post) {
        $productId = $form->getValue("id");
        //modify product base information
        $product = array();
        $product['department_id'] = $form->getValue("department");
        $product['title'] = $form->getValue("title");
        $product['url_title'] = HttpUtil::iReplaceAllUrlStr($form->getValue("urlTitle"));
        $product['description'] = $form->getValue("description");
        $product['related_1'] = $form->getValue("related1");
        $product['related_2'] = $form->getValue("related2");
        $product['related_3'] = $form->getValue("related3");
        $product['related_4'] = $form->getValue("related4");
        $product['seo_title'] = $form->getValue("seoTitle");
        $product['seo_keyword'] = $form->getValue("seoKeyword");
        $product['seo_description'] = $form->getValue("seoDescription");
        $product['cheque_rule'] = $form->getValue("chequeRule");
        $product['price_rule'] = $form->getValue("priceRule");
        $product['ship_rule'] = $form->getValue("shipRule");
        $product['related_rule'] = $form->getValue("relatedRule");
        $product['templete'] = $form->getValue("templete");
        $this->productDao->updateProduct($productId, $product);
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITPRO',$loginUser['uname'], $product,$productId);          
        //modify categoryproduct
        //delete old
        $this->categoryProductDao->deleteByProductId($productId);
        //insert new
        $categoryIdStr = $post["categoryId"];
        if(!empty($categoryIdStr)) {
            $categoryIds = explode(",", $categoryIdStr);
            foreach($categoryIds as $categoryId) {
                $categoryId = trim($categoryId);
                if(!empty($categoryId) && $categoryId != "-1") {
                    $categoryProduct = array("category_id" => $categoryId , "product_id" => $productId);
                    $this->categoryProductDao->insertCategoryProduct($categoryProduct);
                }
            }
        }
        //delete items and item metadata
        $deletedItemStr = $post["deletedItems"];
        $deletedItems = explode(",",$deletedItemStr);
        if(isset($deletedItems)) {
            foreach($deletedItems as $deletedItem) {
                if(!empty($deletedItem)) {
                    $this->itemMetadataDao->deleteItemMetadata($deletedItem);
                    $this->productItemDao->deleteItem($deletedItem);                   
                }
            }
        }
        //modify items
        $attribute = isset($post['attribute']) ? $post['attribute'] : null;
        //attribute value
        $itemIds = $post['itemId'];
        $value1s = isset($post['value0']) ? $post['value0'] : null;
        $value2s = isset($post['value1']) ? $post['value1'] : null;
        $value3s = isset($post['value2']) ? $post['value2'] : null;
        $value4s = isset($post['value3']) ? $post['value3'] : null;
        $value5s = isset($post['value4']) ? $post['value4'] : null;
        $defaultItemValue =  $post['defaultItemVal'];
        $upcs = $post['upc'];
        //$skus = $post['sku'];
        $pPrices = $post['pPrice'];
        $cPrices = $post['cPrice'];
        $mPrices = $post['mPrice'];
        $lPrices = $post['lPrice'];
        $sPrices = $post['sPrice'];
        $weights = $post['weight'];
        $inventories = $post['inventory'];
        //$places = $post['place'];
        //$shippingTypes = $post['shippingType'];
        //$freeShippingStatuses = $post['freeShippingStatus'];
        $visibles = $post['visible'];
        $defaultItems = explode(",",$defaultItemValue);
        //product metadata
        $pMetadataIds = $_POST['pMetadataId'];
        if(!empty($pMetadataIds)){
            $productMetadatas = $this->metadataDao->getMetedataByIds($pMetadataIds);
        }
        //item metadata
        $iMetadataIds = $_POST['iMetadataId'];
        if(!empty($iMetadataIds)){
            $itemMetadatas = $this->metadataDao->getMetedataByIds($iMetadataIds);
        }
        
        $i = 0;
        if(isset($itemIds)) {
            foreach($itemIds as $itemId) {
                $itemId = trim($itemId);
                if($itemId == "") {
                    $i++;
                    continue ;
                }
                $upc = trim($upcs[$i]);
                //$sku = trim($skus[$i]);
                $pPrice = trim($pPrices[$i]);
                $cPrice = trim($cPrices[$i]);
                $mPrice = trim($mPrices[$i]);
                $lPrice = trim($lPrices[$i]);
                $sPrice = trim($sPrices[$i]);
                $weight = trim($weights[$i]);
                $inventory = trim($inventories[$i]);
                //$place = trim($places[$i]);
                $defaultItem = $defaultItems[$i];
                //$shippingType = $shippingTypes[$i];
                //$freeShippingStatus = $freeShippingStatuses[$i];
                $visible = $visibles[$i];
                $attribute1 = "";
                $attribute2 = "";
                $attribute3 = "";
                $attribute4 = "";
                $attribute5 = "";
                $value1 = "";
                $value2 = "";
                $value3 = "";
                $value4 = "";
                $value5 = "";
                $key1 = "";
                $key2 = "";
                $key3 = "";
                $key4 = "";
                $key5 = "";
                $metadataId1 = "";
                $metadataId2 = "";
                $metadataId3 = "";
                $metadataId4 = "";
                $metadataId5 = "";
                if(isset($attribute) && isset($attribute[0]) && isset($value1s)) {
                    $attribute1 = trim($attribute[0]);
                    $itemAttribute1 = $this->getItemMetadataValue(0,trim($value1s[$i]),$iMetadataIds,$itemMetadatas);
                    $value1 = $itemAttribute1['value'];
                    $key1 = $itemAttribute1['key'];
                    $metadataId1 = $itemAttribute1['metadataId'];
                }
                if(isset($attribute) && isset($attribute[1]) && isset($value2s)) {
                    $attribute2 = trim($attribute[1]);
                    $itemAttribute2 = $this->getItemMetadataValue(1,trim($value2s[$i]),$iMetadataIds,$itemMetadatas);
                    $value2 = $itemAttribute2['value'];
                    $key2 = $itemAttribute2['key'];
                    $metadataId2 = $itemAttribute2['metadataId'];
                }
                if(isset($attribute) && isset($attribute[2]) && isset($value3s)) {
                    $attribute3 = trim($attribute[2]);
                    $itemAttribute3 = $this->getItemMetadataValue(2,trim($value3s[$i]),$iMetadataIds,$itemMetadatas);
                    $value3 = $itemAttribute3['value'];
                    $key3 = $itemAttribute3['key'];
                    $metadataId3 = $itemAttribute3['metadataId'];
                }
                if(isset($attribute) && isset($attribute[3]) && isset($value4s)) {
                    $attribute4 = trim($attribute[3]);
                    $itemAttribute4 = $this->getItemMetadataValue(3,trim($value4s[$i]),$iMetadataIds,$itemMetadatas);
                    $value4 = $itemAttribute4['value'];
                    $key4 = $itemAttribute4['key'];
                    $metadataId4 = $itemAttribute4['metadataId'];
                }
                if(isset($attribute) && isset($attribute[4]) && isset($value5s)) {
                    $attribute5 = trim($attribute[4]);
                    $itemAttribute5 = $this->getItemMetadataValue(4,trim($value5s[$i]),$iMetadataIds,$itemMetadatas);
                    $value5 = $itemAttribute5['value'];
                    $key5 = $itemAttribute5['key'];
                    $metadataId5 = $itemAttribute5['metadataId'];
                }
                $productItem = array(
                    "product_id" => $productId,
                    "attribute_1" => $attribute1,
                    "value_1" => $value1,
                    "key_1" => $key1,
                    "metadata_1" => $metadataId1,
                    "attribute_2" => $attribute2,
                    "value_2" => $value2,
                    "key_2" => $key2,
                    "metadata_2" => $metadataId2,
                    "attribute_3" => $attribute3,
                    "value_3" => $value3,
                    "key_3" => $key3,
                    "metadata_3" => $metadataId3,
                    "attribute_4" => $attribute4,
                    "value_4" => $value4,
                    "key_4" => $key4,
                    "metadata_4" => $metadataId4,
                    "attribute_5" => $attribute5,
                    "value_5" => $value5,
                    "key_5" => $key5,
                    "metadata_5" => $metadataId5,
                    //"upc" => $upc,
                    //"sku" => $sku,
                    "purchasing_price" => $pPrice,
                    "cost_price" => $cPrice,
                    "marketing_price" => $mPrice,
                    "list_price" => $lPrice,
                    "sale_price" => $sPrice,
                    "weight" => $weight,
                    "inventory" => $inventory,
                    //"place" => $place,
                    "default_item" => $defaultItem,
                    //"shipping_type" => $shippingType,
                    //"free_shipping_status" => $freeShippingStatus,
                    "visible" => $visible
                );
                //                var_dump($productItem);
                //                echo $itemId;
                //                exit();
                if($itemId == "0") {
                    $itemId = $this->productItemDao->insertData($productItem);
                }else {
                    $this->productItemDao->updateItem($itemId, $productItem);
                }
                //update upc
                if(empty($upc)){
                    $upc = Number::getProductItemNumber($itemId);
                }
                $productItem = array("upc" => $upc);
                $this->productItemDao->updateItem($itemId, $productItem);
                //delete old item metedatas
                $this->itemMetadataDao->deleteItemMetadata($itemId);
                //insert item metedatas
                if(!empty($pMetadataIds)){
                    foreach($pMetadataIds as $pMetadataId){
                        $metadata = $productMetadatas[$pMetadataId];
                        $inputType = $metadata['input_type'];
                        if(is_array($_POST['pMetadata'.$pMetadataId])){
                            $metadataValues = $_POST['pMetadata'.$pMetadataId];
                            if(empty($metadataValues)){
                                 continue ;
                            }
                            foreach($metadataValues as $metadataValue){
                                $itemMetadata = array();
                                $itemMetadata['product_item_id'] = $itemId;
                                $itemMetadata['metadata_id'] = $pMetadataId;
                                if($inputType == 2){
                                    $itemMetadata['desc_value'] = $metadataValue;
                                }else{
                                    $itemMetadata['value'] = $metadataValue;
                                }
                                $this->itemMetadataDao->insertItemMetadata($itemMetadata);                              
                            }
                        }else{                        
                            $metadataValue = trim($_POST['pMetadata'.$pMetadataId]);
                            if(empty($metadataValue)){
                                continue ;
                            }
                            $itemMetadata = array();
                            $itemMetadata['product_item_id'] = $itemId;
                            $itemMetadata['metadata_id'] = $pMetadataId;
                            if($inputType == 2){
                                $itemMetadata['desc_value'] = $metadataValue;
                            }else{
                                $itemMetadata['value'] = $metadataValue;
                            }
                            $this->itemMetadataDao->insertItemMetadata($itemMetadata);
                        }
                    }
                }
                if(!empty($iMetadataIds)){
                    $j = 1;
                    foreach($iMetadataIds as $iMetadataId){
                        $itemMetadata = array();
                        $value = "";
                        if($j == 1){
                            $value = trim($value1s[$i]);
                        }else if($j == 2){
                            $value = trim($value2s[$i]);
                        }else if($j == 3){
                            $value = trim($value3s[$i]);
                        }else if($j == 4){
                            $value = trim($value4s[$i]);
                        }else if($j == 5){
                            $value = trim($value5s[$i]);
                        }
                        $itemMetadata['product_item_id'] = $itemId;
                        $itemMetadata['metadata_id'] = $iMetadataId;
                        $itemMetadata['value'] = $value;
                        $this->itemMetadataDao->insertItemMetadata($itemMetadata);
                        $j++;
                    }
                }
                $i++;
            }
        }
    }

    public function deleteProduct($id) {
    	$this->itemMetadataDao->deleteItemMetadataByProductId($id);
        $this->productItemDao->deleteItemByProductId($id);
        $this->categoryProductDao->deleteByProductId($id);
        $this->productDao->deleteProduct($id);
    }

    public function deleteAllProduct($ids) {
        foreach($ids as $id) {
            if(!empty($id)) {
            	$this->itemMetadataDao->deleteItemMetadataByProductId($id);
                $this->productItemDao->deleteItemByProductId($id);
                $this->categoryProductDao->deleteByProductId($id);
                $this->productDao->deleteProduct($id);
            }
        }
    }

    public function getDepartments() {
        $departmentDao = new DepartmentDao();
        $departmentDao->setDb($this->db);
        $departmentData =  $departmentDao->getDepartments();
        $departments = array();
        foreach($departmentData as $department) {
            $departments[$department['id']] = $department['name'];
        }
        return array($departmentData,$departments);
    }

    public function getRelates() {
        $productData = $this->productDao->getProducts();
        $products = array();
        foreach($productData as $product) {
            $product[$product['id']] = $product['title'];
        }
        return array($productData, $products);
    }

    public function getProducts($view, $form) {   	
        $departments = $this->getDepartments();
        $categories = $this->getCategories();
        $dbGrid = new DBGrid($view);
        $dbGrid->setPost($form);
        $dbGrid->setSortOrder("id","DESC");
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "products-id", $this->_translate->translate("id"));
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "products-title", $this->_translate->translate("title"));
        $dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "category_products-category_id" , $this->_translate->translate("category"),$categories,array(),DBGridConstant::OPERATOR_IN_SQL,"id in (select product_id from category_products where category_id = ? and is_delete = 0)");
        $dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-cheque_rule", $this->_translate->translate("chequeRule"), MetadataConstant::getDefaultChequeRuleList());
        $dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-price_rule", $this->_translate->translate("priceRule"), MetadataConstant::getDefaultPriceRuleList());
        $dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-ship_rule", $this->_translate->translate("shipRule"), MetadataConstant::getDefaultShipRuleList());
        $dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-related_rule", $this->_translate->translate("relatedRule"), MetadataConstant::getDefaultRelatedRuleList());
        //$dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-department_id", $this->_translate->translate("department"), $departments[1]);
        $dbGrid->addFetchTable("products", array("distinct(products.id) as id", "title","url_title","templete","cheque_rule","price_rule","ship_rule","related_rule"));
        //$dbGrid->addFetchTable("departments", "name", "departments.id=products.department_id",DBGridConstant::JOIN_TYPE_OUTER);
        //$dbGrid->addFetchTable("category_products", array("product_id"), "category_products.product_id=products.id and category_products.is_delete = 0",DBGridConstant::JOIN_TYPE_OUTER);
        //$dbGrid->addFetchTable("product_items", "count(product_items.id) as counts", "product_items.product_id=products.id");
        $dbGrid->addValueFilter("products-is_delete", "0");
        $dbGrid->addFetchColumn("id", $this->_translate->translate("id"),"edit");
        $dbGrid->addFetchColumn("title", $this->_translate->translate("title"));
        $dbGrid->addFetchColumn("url_title", $this->_translate->translate("urlTitle"));
        $dbGrid->addFetchColumn("cheque_rule", $this->_translate->translate("chequeRule"),"",MetadataConstant::getDefaultChequeRuleList());
        $dbGrid->addFetchColumn("price_rule", $this->_translate->translate("priceRule"),"",MetadataConstant::getDefaultPriceRuleList());
        $dbGrid->addFetchColumn("ship_rule", $this->_translate->translate("shipRule"),"",MetadataConstant::getDefaultShipRuleList());
        $dbGrid->addFetchColumn("related_rule", $this->_translate->translate("relatedRule"),"",MetadataConstant::getDefaultRelatedRuleList());
        $dbGrid->addFetchColumn("templete", $this->_translate->translate("templete"));
        //$dbGrid->addFetchColumn("counts", $this->_translate->translate("items"));
        //$dbGrid->addFetchColumn("name", $this->_translate->translate("department"));
        //module action
        $dbGrid->addAAModuleAction("product","edit",$this->_translate->translate("editBtn"),"edit");
        $dbGrid->addAAModuleAction("product","delete",$this->_translate->translate("delBtn"),"deletesome");
        $dbGrid->addAAModuleAction("product","add",$this->_translate->translate("addBtn"),"select");
        $dbGrid->setPageTitle($this->_translate->translate("productList"));
        $dbGrid->setModule('/inventory/product');
        return $dbGrid->render();
    }

    public function getRelateProduct($view, $form){
        $departments = $this->getDepartments();
        $dbGrid = new DBGrid($view);
        $dbGrid->setPost($form);
        $dbGrid->setSortOrder("id","desc");
        $dbGrid->setFilterAction(HttpUtil::baseUrl() . "/inventory/product/searchrelate");
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "products-title", $this->_translate->translate("title"));
        //$dbGrid->addOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "products-department_id", $this->_translate->translate("department"), $departments[1]);
        $dbGrid->addFetchTable("products", array("id", "title"));
        //$dbGrid->addFetchTable("departments", "name", "departments.id=products.department_id");
        $dbGrid->addValueFilter("products-is_delete", "0");
        $dbGrid->addFetchColumn("id", $this->_translate->translate("id"));
        $dbGrid->addFetchColumn("title", $this->_translate->translate("title"));
        //$dbGrid->addFetchColumn("name", $this->_translate->translate("department"));   
        $dbGrid->setPageTitle($this->_translate->translate("searchProduct"));
        $dbGrid->setModule('/inventory/product');
        $dbGrid->setReturnData(true);
        $dbGrid->setCallBackMethod("Inventory.getRelate");
        return $dbGrid->renderAjaxDbGrid();
    }
    
    public function searchItem($view, $post ,$from){
        $dbGrid = new DBGrid($view);
        $dbGrid->setPost($post);
        $dbGrid->setFilterAction(HttpUtil::baseUrl() . "/inventory/product/searchitem/from/" . $from);
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "products-title", $this->_translate->translate("title"));
        $dbGrid->addFetchTable("product_items", "*");
        $dbGrid->addFetchTable("products",array("title"),"product_items.product_id = products.id");
        $dbGrid->addValueFilter("product_items-is_delete", "0");
        $dbGrid->addFetchColumn("id", $this->_translate->translate("id"));
        $dbGrid->addFetchColumn("title", $this->_translate->translate("title"));
        $dbGrid->addFetchColumn("upc", $this->_translate->translate("upc"));
        $dbGrid->addFetchColumn("sku", $this->_translate->translate("sku"));
        $dbGrid->addFetchHiddenColumn("attribute_1");
        $dbGrid->addFetchHiddenColumn("value_1");
        $dbGrid->addFetchHiddenColumn("attribute_2");
        $dbGrid->addFetchHiddenColumn("value_2");
        $dbGrid->addFetchHiddenColumn("attribute_3");
        $dbGrid->addFetchHiddenColumn("value_3");
        $dbGrid->addFetchHiddenColumn("attribute_4");
        $dbGrid->addFetchHiddenColumn("value_4");
        $dbGrid->addFetchHiddenColumn("attribute_5");
        $dbGrid->addFetchHiddenColumn("value_5");
        $dbGrid->setPageTitle($this->_translate->translate("searchProduct"));
        $dbGrid->setModule('/inventory/product');
        $dbGrid->setReturnData(true);
        if($from == "promotion"){
           $dbGrid->setCallBackMethod("Promotion.searchItem");
        } 
        if($from == "gift") {
        	$dbGrid->setCallBackMethod("Gift.searchItem");    
        }
        return $dbGrid->renderAjaxDbGrid();
    }

    public function getProductById($id) {
        return $this->productDao->getByCol("id", $id);
    }

    public function getItemsByProduct($productId) {
        return $this->productItemDao->fetchItemsByPid($productId, 0);
    }

    public function getCategoryProductsByProductId($productId) {
        return $this->categoryProductDao->getByProductId($productId);
    }

    public function getSetById($setId){
        return $this->metadataSetDao->getByCol("id", $setId);
    }

    public function getMetadataBySet($setId,$type){
        $metadatas = $this->metadataDao->getMetadataBySet($setId,$type);
        $i=0;
        for($i;$i<sizeof($metadatas);$i++){
            $inputType = $metadatas[$i]['input_type'];
            $metadataId = $metadatas[$i]['id'];
            if($inputType == 3 || $inputType == 4 || $inputType == 6){
                $metadataOptions = $this->metadataOptionDao->getOptionsByMetadataId($metadataId);
                $metadatas[$i]['options'] = $metadataOptions;
            }
        }
        return $metadatas;
    }

    public function getProductMetatdataValue($productId){
        $result = array();
        $itemMetadatas = $this->itemMetadataDao->getDistinctMetadataValue($productId);
        if(!empty($itemMetadatas)){
            foreach($itemMetadatas as $itemMetadata){
                $metadataId = $itemMetadata["metadata_id"];
                $inputType = $itemMetadata["input_type"];
                if($inputType == 2){
                    //description value
                    $result[$metadataId] = $itemMetadata["desc_value"];
                }else if($inputType == 4){
                    $result[$metadataId][] = $itemMetadata["value"];
                }else{
                    $result[$metadataId] = $itemMetadata["value"];
                }
            }
        }
        return $result;
    }

    public function getSets(){
       $sets = $this->metadataSetDao->getMetadataSet();
       return $sets;
    }

    public function getCategories(){
        $result = array();
        $categories = $this->categoryDao->getCategories();
        foreach($categories as $category){
            $result[$category['id']] = $category['short_name'];
        }
        return $result;
    }
    
    //查找每个item的图片
    public function getItemImageByItemId($itemId){
        $productImages = $this->productImageDao->getItemImagesByItemId($itemId);
        return $productImages;
    }
    
    //查找单个图片的属性
    public function getImageById($id){
    	$imageInfo = $this->productImageDao->getImageById($id);
        return $imageInfo;
    }
    
    //删除图片
    public function deleteItemImage($id){
//    	$param = array("id" => $id);
//    	$this->productImageDao->deleteImage($param);
    	
    	$itemImage = $this->productImageDao->getImageById($id);
    	$pid = $itemImage[0]["product_id"];
    	$itemId = $itemImage[0]["item_id"];
    	$name = $itemImage[0]["name"];
    	$folder = $itemImage[0]["folder"];
    	
    	//echo $pid."==".$itemId."=$folder=".$name;
    	
    }
    
    //编辑图片属性//defaultImageId is the is of the default Image Id
//    public function editImageAttribute($id, $itemId, $isDefaultImage, $sortOrder){
    public function editImageAttribute($itemId, $imageIdArray, $sortArray, $defaultImageId){
        foreach ($imageIdArray as $key => $imageId) {
        	$sort = $sortArray[$key];
        	if(!is_numeric($sort)){
        		$sort = 0;
        	}else{
        		$sort += 0;
	        	if(!is_int($sort)){
	                $sort = 0;
	            }
        	}
        	if($defaultImageId == $imageId){
        		$this->productImageDao->updateImageById($imageId, $sort, 1);
        	}else{
        		$this->productImageDao->updateImageById($imageId, $sort, 0);
        	}
        }
    	
    	/*
    	//设置当前的图片为默认图片
        if($isDefaultImage == "true"){
        	//将原先的所有图片设置为非默认图片
            $this->productImageDao->updateDefaultImageStatusByItemId($itemId);
            //设置当前的图片为默认图片
            $this->productImageDao->updateDefaultImageById($id);
            //更新item表中默认图片信息
            $this->productItemDao->updateDefaultImageByItenId($itemId, $id);
        }else{
        	//设置当前的图片为非默认图片
            $this->productImageDao->updateNotDefaultImageStatusById($id);
        }
        //设置当前图片的顺序
    	$this->productImageDao->updateImageSortById($id, $sortOrder);
    	*/
    }
    
    //判断是否设置了默认图片
    public function isSetDefaultImage($itemId){
    	$itemImageInfo = $this->productImageDao->getItemImagesByItemId($itemId);
    	if(empty($itemImageInfo)){//如果item还没有图片，不判断是否有默认图片
    		return true;
    	}else{//如果item有图片
	    	$result = $this->productImageDao->getDefaultImageByItemId($itemId);
	        if(empty($result)){//没有默认图片
	            return false;
	        }else{//有默认图片
	            return true;
	        }
    	}
    	
    }
    
} 
?>